package com.xr.common.config;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.xr.common.constants.RedisConstant;
import com.xr.common.entity.SimpleUser;
import com.xr.common.redis.RedisCacheService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

@Slf4j
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {

	private final RedisCacheService redisCacheService;

	public MybatisPlusMetaObjectHandler(RedisCacheService redisCacheService) {
		this.redisCacheService = redisCacheService;
	}

	/**
	 * 插入时的填充策略
	 * @param metaObject
	 */
	@Override
	public void insertFill(MetaObject metaObject) {
		String userJsonStr = redisCacheService.get(RedisConstant.CURRENT_LOGIN_USER_KEY);
		SimpleUser simpleUser = JSONUtil.toBean(userJsonStr, SimpleUser.class);
		Long currentLoginUserId = simpleUser.getUserId() != null ? simpleUser.getUserId() : 0L;
		log.info("公共字段开始自动填充[insert]...,[metaObject:{}]", metaObject.toString());
		this.setFieldValByName("createId", currentLoginUserId, metaObject);
		this.setFieldValByName("createTime", new Date(), metaObject);
		this.setFieldValByName("updateId", currentLoginUserId, metaObject);
		this.setFieldValByName("updateTime", new Date(), metaObject);
	}

	/**
	 * 更新时的填充策略
	 * @param metaObject
	 */
	@Override
	public void updateFill(MetaObject metaObject) {
		String userJsonStr = redisCacheService.get(RedisConstant.CURRENT_LOGIN_USER_KEY);
		SimpleUser simpleUser = JSONUtil.toBean(userJsonStr, SimpleUser.class);
		Long currentLoginUserId = simpleUser.getUserId() != null ? simpleUser.getUserId() : 0L;
		log.info("公共字段开始自动填充[update]...,[metaObject:{}]", metaObject.toString());
		this.setFieldValByName("updateId", currentLoginUserId, metaObject);
		this.setFieldValByName("updateTime", new Date(), metaObject);
	}

}
